/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;
import opiam.admin.applis.demo.forms.PersonForm;

import opiam.admin.faare.SearchResult;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.List;


/**
 * This action allows to add a selected user to the manager attribute
 *  of the current entry at the modification.
 */
public class SelectUserAction extends SecureAction
{
    /** Logger de log4j. */
    private static Logger _logger = Logger.getLogger(SelectUserAction.class);

    /**
     * Struts Action method.
     * See SecureAction
     *
     * @param mapping Struts mapping data.
     * @param actionForm Input form.
     * @param request HTTP request.
     * @param httpServletResponse HTTP response.
     *
     * @return forward to success or to error
     *
     * @throws java.io.IOException see Action.execute()
     * @throws javax.servlet.ServletException see Action.execute()
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        ActionMessages msgErrors = new ActionMessages();

        String[] users = request.getParameterValues("userIndex");

        if (users == null)
        {
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("No selection")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("error"));
        }

        SessionContext sessionContext = null;
        UserContext userContext = null;

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();

            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            // Gets the user context.
            userContext = sessionContext.getUserContext();

            // Connected user
            Person cuser = (Person) userContext.getJbUser();

            // Gets the profile
            String profile = cuser.getProfile();

            SearchResult searchResult =
                (SearchResult) session.getAttribute("usersSearchResult");

            if (searchResult != null)
            {
                List currentUsers = searchResult.getLResults();

                if ((currentUsers != null) && (currentUsers.size() > 0))
                {
                    int index = Integer.parseInt(users[0]);
                    PersonForm pf =
                        (PersonForm) session.getAttribute("personForm");
                    Person manager = (Person) currentUsers.get(index);
                    pf.setManager(manager.getCommonName());
                    pf.setManagerPerson(manager);
                    _logger.debug("manager : " + manager.getDn());
                    session.setAttribute("personForm", pf);

                    String forward = "error";

                    if (profile.equals("Accounting Manager") ||
                            profile.equals("HR Manager") ||
                            profile.equals("PD Manager") ||
                            profile.equals("QA Manager")
                       )
                    {
                        forward = "success_manager";
                    }
                    else if (profile.equals("Directory Administrator"))
                    {
                        forward = "success_directoryadministrator";
                    }

                    return (mapping.findForward(forward));
                }
            }

            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("Can't find usersSearchResult in Session")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("error"));
        }
        catch (Exception se)
        {
            _logger.debug("Trace", se);
            _logger.error(se.getMessage());
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("error"));
        }
    }
}
